package com.app.bimo.module_bookrack.mvp.ui.fragment;

import android.app.Dialog;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.app.bimo.commonbusiness.base.BaseFragment;
import com.app.bimo.commonbusiness.util.Constant;
import com.app.bimo.commonbusiness.util.DataUtil;
import com.app.bimo.commonbusiness.util.GlideImagSetUtil;
import com.app.bimo.commonbusiness.util.JumpPageUtil;
import com.app.bimo.commonbusiness.util.LoginService;
import com.app.bimo.commonbusiness.util.RouterHub;
import com.app.bimo.commonbusiness.util.SharedPreUtils;
import com.app.bimo.commonbusiness.util.SystemUtil;
import com.app.bimo.commonbusiness.util.UiUtil;
import com.app.bimo.commonbusiness.view.recyclerview.HeadFootRecyclerView;
import com.app.bimo.library_db.ADConfigData;
import com.app.bimo.library_db.BookData;
import com.app.bimo.library_db.helper.AdHelper;
import com.app.bimo.module_bookrack.R;
import com.app.bimo.module_bookrack.mvp.constract.BookrackContract;
import com.app.bimo.module_bookrack.mvp.model.entiy.OtherResult;
import com.app.bimo.module_bookrack.mvp.model.model.BookrackModel;
import com.app.bimo.module_bookrack.mvp.persenter.BookrackPresenter;
import com.app.bimo.module_bookrack.mvp.ui.activity.BookrackSearchActivity;
import com.app.bimo.module_bookrack.mvp.ui.adapter.BookrackAdapter;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


public class BookRackFragment extends BaseFragment<BookrackPresenter> implements BookrackContract.View, OnRefreshListener, OnLoadMoreListener,View.OnClickListener {

    private HeadFootRecyclerView listView;
    private RecyclerView.ItemDecoration divV;
    private BookrackAdapter adapter;
    private List<BookData> list = new ArrayList<>();
    private GridLayoutManager gridLayoutManager;
    private boolean isGrid = true;//列表排列方式


    private Dialog menuDialog;
    private TextView menuChangeListBtn;
    private TextView title;
    private Toolbar mtoolbar;
    private FrameLayout banner_container;
    private View headView;
    private View readRecord;
    private ImageView book;
    private ImageView headBg;
    private TextView bookName;
    private TextView hint;
    private View footView;
    private Button mCreativeButton;
    private TextView scrollContentTextView;
    private ImageView scrollContentIcon;
    private View bannerView;
    private SmartRefreshLayout refresh; // 刷新
    private int page = 1; // 当前刷新页码

    //推荐阅读
    private BookData recommendData;
    private List<OtherResult> headBanners = new ArrayList<>();

    private Bundle bundle = new Bundle();
    private TTAdManager adManager;
    private TTAdNative ttAdNative;
    private TTNativeExpressAd mTTAd;


    @Autowired(name = Constant.BOOKSELF_ARRANGMENT_MODE)
    String isDelBack;
    int interval = 10;







    @Override
    public int setLayoutID() {
        return R.layout.bookrack_home_fragment;
    }

    @Override
    protected void initView() {

        mPresenter = new BookrackPresenter(new BookrackModel(), this);
        //获取布局样式
        isGrid = SharedPreUtils.getInstance(getContext()).getInt(Constant.BOOKSELF_ARRANGMENT_MODE, 1) == 1;
        divV = mPresenter.div();
        initToolbar();
        initViews();
        //初始化 SmartRefreshLayout  事件
        initRefresh();
//        getData();
//        hideLoading();


    }

    @Override
    protected void initData() {


    }

    @Override
    protected void initEvent() {

    }

    @Override
    public void onResume() {
        super.onResume();
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        onRefresh(refresh);
    }

    @Override
    public void onClick(View v) {
        JumpPageUtil.jumpActivity(getActivity(), BookrackSearchActivity.class,false);
        int i = v.getId();
        if (i == R.id.right) {
            JumpPageUtil.jumpActivity(getActivity(), BookrackSearchActivity.class,false);
        }
    }

    //点击重新加载
    @Override
    public void onBaseRefresh() {
        showLoading();
        onRefresh(refresh);
    }

    /**
     *   书架页列表数据回调
     * @param mlist
     * @param mpage
     * @param isChange  是否改变数据
     */
    @Override
    public void bookrackDataNotify(List<BookData> mlist, int mpage, boolean isChange) {
        finishRefresh(mlist.size() != 0);
        if (!isChange) {
            return;
        }
        if (mpage == 1) {
            if (mlist == null || mlist.size() == 0){
                footView.setVisibility(View.VISIBLE);
            }
            refresh.finishRefresh();
            list.clear();
        }
        list.addAll(mlist);
        if (mpage == 1) {
            if (!((LoginService) ARouter.getInstance().build(RouterHub.ACCOUNT_SERVICE).navigation()).isVip()) {
                setFootView(false);
            } else{
                setFootView(list.size() == 0);
            }
        } else {
            adapter.notifyItemRangeChanged(1, list.size());
        }

    }

    private void finishRefresh(boolean isHaveMore) {
        refresh.finishRefresh(true);
        if (isHaveMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishLoadMoreWithNoMoreData();
        }
    }


    /**
     * 返回推荐阅读  或最近阅读
     * @param data
     */
    @Override
    public void getBookshelfRecommendNotify(BookData data) {
        this.recommendData = data;
        setRecommendData(recommendData);
    }

    private void setRecommendData(BookData data) {
        if (data == null) {
            readRecord.setVisibility(View.INVISIBLE);
            return;
        } else {
            readRecord.setVisibility(View.VISIBLE);
        }
        bookName.setText(data.getNovelName());
        if (!DataUtil.isEmpty(data.getTips())) {
            hint.setText(data.getTips());
        }
        GlideImagSetUtil.loadImgRoundedCornersCenterCrop(data.getCover(), book, SystemUtil.dip2px(getContext(), 3));
    }


    @Override
    public void bookrackErrorDataNotify(String s) {

    }

    /**
     * 阅读时长请求数据回调
     * @param data
     */
    @Override
    public void weekReadTimeNotify(OtherResult data) {
        long time = data.getReadTime() / 60;
        String s = "<font ><big>0</big>分钟</font >";
        if (time > 120) {
            s = "<font><big>" + (time / 60) + "</big>" + getString(R.string.read_time_hour) + "</font >";
        } else {
            if (data.getReadTime() > 0 && time == 0) {
                s = "<font><big>1</big>" + getString(R.string.read_time_min) + "</font >";
            } else {
                s = "<font><big>" + time + "</big>" + getString(R.string.read_time_min) + "</font >";
            }
            title.setText(Html.fromHtml("本周累计阅读" + s));
        }
    }

    /**
     * 获取公告内容
     * @param list
     */
    @Override
    public void getAnnounceNotify(List<OtherResult> list) {
        if (list.size() > 0) {
            scrollContentIcon.setVisibility(View.VISIBLE);
            scrollContentTextView.setVisibility(View.VISIBLE);
            scrollContentTextView.setText(list.get(0).getContent());
        } else {
            scrollContentTextView.setVisibility(View.GONE);
            scrollContentIcon.setVisibility(View.GONE);
        }
    }

    @Override
    public void getBannerNotify(List<OtherResult> list) {
        if (list != null) {
            headBanners.clear();
            headBanners.addAll(list);
            GlideImagSetUtil.loadImageCenterCrop(list.get(0).getImgurl(), headBg);
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        mPresenter.getBooks(page);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

//        if (!((LoginService) ARouter.getInstance().build(RouterHub.ACCOUNT_SERVICE).navigation()).isVip()) {
//            ADConfigData data = AdHelper.getsInstance().getAdBookshelfBanner();
//            if (data != null) {
//                if (data.getStatus().equals("1")) {
//                    loadBannerAd(data.getAdid());
//                }
//            }
//        }else{
//            banner_container.removeAllViews();
//            banner_container.setVisibility(View.GONE);
//        }
//        showDialogLoading();
        page = 1;
        mPresenter.getBooks(page);
        mPresenter.getRecommend();
        mPresenter.getAnnounce();
        mPresenter.getBanner();
        mPresenter.readTimeRequestFromModel();

        refresh.resetNoMoreData();

    }


    private void initToolbar() {
        mtoolbar = getView(R.id.mtoolbar);
        mtoolbar.setNavigationIcon(null);
        TextView right = getView(R.id.right);
        title = getView(R.id.title);
        TextView right1 = getView(R.id.right1);
        mtoolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
        UiUtil.setImgToTextView(right, R.drawable.res_search_b, 4);
        UiUtil.setImgToTextView(right1, R.drawable.bookrack_head_edit, 4);
        right1.setOnClickListener(this);
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("testCache","testCache");
                JumpPageUtil.jumpActivity(getActivity(), BookrackSearchActivity.class,false);
            }
        });
    }


    private void initViews() {
        initHeadView();
        listView = getView(R.id.list);
        DefaultItemAnimator defaultItemAnimator = new DefaultItemAnimator();
        defaultItemAnimator.setRemoveDuration(500);
        defaultItemAnimator.setAddDuration(500);
        defaultItemAnimator.setChangeDuration(500);
        defaultItemAnimator.setMoveDuration(500);
        listView.setItemAnimator(defaultItemAnimator);
        if (isGrid) {
            initGridListView();
        } else {
            initLinListView();
        }

    }

    private void initHeadView() {
        headView = View.inflate(getContext(), R.layout.bookrack_home_head, null);
        banner_container = headView.findViewById(R.id.adContiner);
        book = getView(R.id.book);
        headBg = getView(R.id.headBg);
        bookName = getView(R.id.bookName);
        hint = getView(R.id.hint);
        readRecord = getView(R.id.readRecord);
        scrollContentTextView = headView.findViewById(R.id.scrollContentTextView);
        scrollContentIcon = headView.findViewById(R.id.scrollContentIcon);
        readRecord.setOnClickListener(this);
        headBg.setOnClickListener(this);
        scrollContentTextView.setSelected(true);
        footView = View.inflate(getContext(), R.layout.empty_lay, null);
        ViewGroup.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.height = SystemUtil.getHigh(getContext()) - SystemUtil.getBookrackHeadHeight(getContext()) - SystemUtil.dip2px(getContext(), 50);
        footView.setLayoutParams(lp);
//        footView.setVisibility(View.VISIBLE);
        footView.findViewById(R.id.retryBtn).setOnClickListener(this);
    }


    private void initLinListView() {
        gridLayoutManager = new GridLayoutManager(getContext(), 1);
        listView.setLayoutManager(gridLayoutManager);
        adapter = new BookrackAdapter(getContext(), list, listView);
        listView.addHeaderView(headView);
        setFootView(list.size() == 0);

    }

    private void initGridListView() {
        gridLayoutManager = new GridLayoutManager(getContext(), 3);
        listView.setLayoutManager(gridLayoutManager);
        adapter = new BookrackAdapter(getContext(), list, listView);
        listView.addHeaderView(headView);
        setFootView(list.size() == 0);
    }

    /**
     * 数据为空 设置空白展位图
     *
     * @param isEmpty
     */
    private void setFootView(boolean isEmpty) {
        listView.removeItemDecoration(divV);
        if (gridLayoutManager.getSpanCount() == 3 && !isEmpty) {
            listView.addItemDecoration(divV);
        }
        listView.addFooterView(isEmpty ? footView : null);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }


    private void initRefresh() {
        refresh = getView(R.id.refresh);
        refresh.setOnRefreshListener(this);
        refresh.setOnLoadMoreListener(this);
    }

}
